import logging
import os
import sys
from logging.handlers import TimedRotatingFileHandler

def setup_logging(log_level: str = "INFO", log_dir: str = "logs"):
    """设置应用日志配置"""
    
    # 创建日志目录
    os.makedirs(log_dir, exist_ok=True)
    
    # 配置根日志记录器
    root_logger = logging.getLogger()
    root_logger.setLevel(getattr(logging, log_level.upper()))
    
    # 检查是否已经有文件处理器，避免重复添加
    has_file_handler = any(
        isinstance(handler, (logging.FileHandler, TimedRotatingFileHandler))
        for handler in root_logger.handlers
    )
    
    # 如果已经有文件处理器，则跳过设置
    if has_file_handler:
        return
    
    # 清除已有的处理器，避免重复
    for handler in root_logger.handlers[:]:
        root_logger.removeHandler(handler)
    
    # 日志格式
    formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(filename)s:%(lineno)d - %(message)s'
    )
    
    # 文件处理器 - 按日期轮转
    log_file = os.path.join(log_dir, "scorpio.log")
    file_handler = TimedRotatingFileHandler(
        filename=log_file,
        when='midnight',    # 每天轮转
        interval=1,
        backupCount=30,     # 保留30天
        encoding='utf-8'
    )
    file_handler.setFormatter(formatter)
    file_handler.suffix = "%Y-%m-%d"  # 备份文件后缀
    
    # 控制台处理器
    console_handler = logging.StreamHandler(sys.stdout)
    console_handler.setFormatter(formatter)
    
    # 添加处理器到根日志记录器
    root_logger.addHandler(file_handler)
    root_logger.addHandler(console_handler)
    
    # 设置一些第三方库的日志级别
    logging.getLogger("uvicorn").setLevel(logging.WARNING)
    logging.getLogger("uvicorn.access").setLevel(logging.WARNING)
    if log_level.upper() == "INFO":
        logging.getLogger("httpx").setLevel(logging.WARN)
        logging.getLogger("httpcore").setLevel(logging.WARN)
    
    # 记录日志配置信息
    root_logger.debug(f"Logging system configured - Level: {log_level}, Directory: {log_dir}")

def get_logger(name: str) -> logging.Logger:
    """获取指定名称的日志记录器"""
    return logging.getLogger(name)